<?php

/**
 * 接口基类
 * 作者：刘单风
 * 最后修改时间：2018-11-14
 * 版权：医库PHP小组
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Cookie;
use MoCommon\Support\Codes;
class Apibase extends Controller
{
    /**
     * 获取用户id
     * @param int $type 0必须登录;1不登录也可以访问,用户id为0
     * @return int
     */
    protected function getUid($type=0)
    {
        $options = Config::get('app.converse');
        $redis = Cache::init($options);

        $userid = 0;
        if (($sign = input('sign')) && ($json_info = $redis->get($sign))) {

            $userid = json_decode($json_info, true)['id'];

        }
        if (($sign = Cookie::get('sign')) && ($json_info = $redis->get($sign))) {
            $userid = json_decode($json_info, true)['id'];
        }
        if (empty($userid)) {
            if ($type) {
                return 0;
            } else {
                //用户未登录
                $result = array(
                    'status' => Codes::NO_SIGNIN,
                    'msg' => Codes::get(Codes::NO_SIGNIN),
                    'data' => []
                );
                echo json_encode($result);
                exit;
            }

        } else {
            return $userid;
        }
    }

    /**
     * 响应格式.
     *
     */
    public function respond($content = [], $status = '', $msg = '')
    {
        $result = [
            'status' => $status ?: Codes::ACTION_SUC,
            'msg' => $msg ?: Codes::get(Codes::ACTION_SUC),
            'data' => $content
        ];
        return json($result);
    }

}